package com.masu.knows.sys.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.masu.knows.commons.exception.ServiceException;
import com.masu.knows.commons.model.*;
import com.masu.knows.sys.dto.RegisterDTO;
import com.masu.knows.sys.mapper.*;
import com.masu.knows.sys.service.IUserService;
import com.masu.knows.sys.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 沈传尚
 * @since 2021-12-07
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    private ClassroomMapper classroomMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserRoleMapper roleMapper;

    @Resource
    private QuestionMapper questionMapper;

    @Resource
    private UserCollectMapper collectMapper;

    @Override
    public void registerStudent(RegisterDTO registerDTO) {
        // 1.根据邀请码获取班级信息
        QueryWrapper<Classroom> wrapper=new QueryWrapper<>();
        wrapper.eq("invite_code",registerDTO.getInviteCode());
        Classroom classroom = classroomMapper.selectOne(wrapper);
        // 2.班级不存在抛出异常
        if (classroom==null){
            throw new ServiceException("邀请码不存在");
        }
        // 3.根据用户输入手机号查询用户信息 username = phone
        User user = userMapper.findUserByUsername(registerDTO.getPhone());
        if (user != null){
            throw new ServiceException("用户已经存在!");
        }
        // 4.判断用户前后输入的两次密码是否一致
        if (!registerDTO.getPassword().equals(registerDTO.getConfirm())){
            throw new ServiceException("前后两次密码不一致");
        }
        // 5.确定一致后 对用户输入的密码进行加密
        PasswordEncoder encoder=new BCryptPasswordEncoder();
        String pwd="{bcrypt}"+encoder.encode(registerDTO.getPassword());
        // 6.实例化对象
        User u=new User();
        u.setUsername(registerDTO.getPhone());
        u.setNickname(registerDTO.getNickname());
        u.setPassword(pwd);
        u.setSex("保密");
        u.setClassroomId(classroom.getId());
        u.setCreatetime(LocalDateTime.now());
        u.setEnabled(1);
        u.setLocked(0);
        u.setType(0);   // 学生类型
        // 7.做新增操作
        int row = userMapper.insert(u);
        if (row == 0){
            throw new ServiceException("新增用户表数据异常");
        }
        // 8.新增用户和角色的关系
        UserRole userRole=new UserRole();
        userRole.setUserId(u.getId());
        userRole.setRoleId(2);
        int rows = roleMapper.insert(userRole);
        if (rows == 0){
            throw new ServiceException("新增用户角色表数据异常");
        }
    }

    @Override
    public List<User> findAllTeacher() {
            if (teachers.isEmpty()){
                synchronized (teachers){
                    if (teachers.isEmpty()){
                        List<User> users = userMapper.selectList(new QueryWrapper<User>().eq("type", 1));
                        teachers.addAll(users);
                        for (User user : teachers){
                            teacherMap.put(user.getNickname(),user);
                        }
                    }
                }
            }
        return teachers;
    }

    private List<User> teachers=new CopyOnWriteArrayList<>();
    private Map<String ,User> teacherMap=new ConcurrentHashMap<>();

    @Override
    public Map<String, User> findTeacherMap() {
        if (teacherMap.isEmpty()){
            findAllTeacher();
        }
        return teacherMap;
    }

    @Override
    public Integer findQuestionsCountsByUserId(Integer userId) {
        QueryWrapper<Question> wrapper=new QueryWrapper();
        wrapper.eq("user_id",userId);
        wrapper.eq("delete_status",0);
        return questionMapper.selectCount(wrapper);
    }

    @Override
    public Integer findCollectionsByUserId(Integer userId) {
        QueryWrapper<UserCollect> wrapper=new QueryWrapper<>();
        wrapper.eq("user_id",userId);
        return collectMapper.selectCount(wrapper);
    }

    @Override
    public UserVo getUserVO(String username) {
        UserVo userVo = userMapper.findUserVOByUsername(username);
        // 根据当前用户获取当前用户的问题数
//        Integer questionCounts = findQuestionsCountsByUserId(userVo.getId());
//        userVo.setQuestions(questionCounts);
        // 根据当前用户id获取当前用户的问题收藏数
//        Integer collections = findCollectionsByUserId(userVo.getId());
//        userVo.setCollections(collections);
        return userVo;
    }

    @Override
    public User getUserByUsername(String username) {
        return userMapper.findUserByUsername(username);
    }

    @Override
    public List<Permission> getPermissionsById(Integer id) {
        return userMapper.getPermissionsByUserId(id);
    }

    @Override
    public List<Role> getRolesById(Integer id) {
        return userMapper.findAllRolesById(id);
    }

}
